const path = require('path');
const url = require('url');
const { app, BrowserWindow, ipcMain } = require('electron');
const notifier = require('node-notifier');
const autocompleter = require('js-autocomplete');

const DataStore = require('../DataStore');
const userData = new DataStore("users")

let loginPage;
let adminPage;

const defaultProps = {
    width: 500,
    height: 800,
    show: false,

    // update for electron V5+
    webPreferences: {
        nodeIntegration: true
    }
}

function forceClose(window) {

  // try close first
  window.close()

  // force with destroy
  if(!window.closed) {
    window.destroy()
  }

  //just logging out the event
  window.on('closed', (e) => {
    console.log(e)
  })

}

function main() {

    let loginWindow = new BrowserWindow(defaultProps);
    loginWindow.loadURL(`file://${__dirname}/login.html`);

    let adminPage = new BrowserWindow(defaultProps);
    adminPage.loadURL(`file://${__dirname}/admin.html`);

    loginWindow.show()

    ipcMain.on('password-accepted', (event, arg) => {
        data = userData.find_row({ password: arg })
        if (data.length == 0) {
            loginWindow.webContents.send("password-message", "Wrong password")
        } else {
            notifier.notify("You are logged in!")
            adminPage.show()
            forceClose(loginWindow)
            adminPage.send('users', userData.get_all_data())
        }
    });

    ipcMain.on('user-add', (event, arg) => {
        userData.insert_data(arg)
        notifier.notify("Add new user")
        adminPage.send('users', userData.get_all_data())
    });

    ipcMain.on('user-del', (event, arg) => {
        userData.delete_data(+arg)
        notifier.notify("User delete")
        adminPage.send('users', userData.get_all_data())
    });

}

app.on('ready', main)

app.on('window-all-closed', function() {
    app.quit()
})
